package com.ldg.gateway.config;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 类名：
 * 功能：配置全局过滤器
 */
// @Configuration
public class AuthGlobalFilter implements GlobalFilter, Ordered {

	//1. 处理过滤逻辑
	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		//1.1 得到请求参数
		String token = exchange.getRequest().getQueryParams().getFirst("token");
		//1.2 判断是否有值
		if(StringUtils.isBlank(token)){
			System.out.println("鉴权失败。");
			// 1.2.1 修改状态码
			exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
			//1.2.2 结束响应并返回
			return exchange.getResponse().setComplete();
		}
		//1.3 继续向下执行
		return chain.filter(exchange);
	}

	//2. 定义此全局过滤器在过滤链中的顺序
	@Override
	public int getOrder() {
		return 0;
	}
}
